/**
 * Created by yindume on 2018/12/10.
 */
var express = require('express');
var router = express.Router();
var db = require('../../../libs/mysql');
//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});
router.get('/',function (req,res) {

    var page = 1; //默认为1
    var num = 10; //一页条数
    if (req.query.page) {
        page = parseInt(req.query.page);
    }
    var count = 0;
    var pages = 0;

    db.query(`select count(*) from category;`,(err,data)=>{
        if(err){
            res.status(500).send('分类总数').end();
        }else {
            count = data[0]['count(*)'];
            pages = Math.ceil(count/num);//总页数
            var str = 'SELECT * FROM category order by id desc limit ' + num + ' offset ' + num * (page - 1);
            db.query(str,(err,data)=>{
                if(err){
                    res.status(500).send('没有上页').end();
                }else {
                    if (!data[0]) {
                        return;
                    }
                    res.render('admin/category/category', {
                        userInfo:req.userInfo,
                        count:count,
                        pages:pages,
                        page: page,
                        num:num,
                        nameList: data
                    });
                }
            });

        }
    })


});

router.use('/add',require('./add'));//添加
router.use('/edit',require('./edit'));//修改
router.use('/del',function(req,res){//删除
    var id = req.query.id;
    db.query(`delete from category where id = '${id}';`,(err,data) => {
        if(err){
            res.send('分类删除').end();
        }else {
            res.redirect('/admin/category');
        }
    })
});


module.exports = router;